package top.marken.demo.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.marken.demo.entity.Order;
import top.marken.demo.entity.User;
import top.marken.demo.entity.info.PageInfo;
import top.marken.demo.service.UserService;
import top.marken.demo.util.JsonData;
import top.marken.demo.util.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 用户登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "user/login";
    }

    /**
     * 用户登录检查
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST, params = {"username","password"})
    public String check(String username, String password, Model model, HttpServletRequest request) {
        if (userService.login(username, password)) {
            User user = userService.userInfo(username);
            request.getSession().setAttribute("user",user);
            model.addAttribute("userOrders",userService.userOrders(user.getId()));
            return "redirect:/user/welcome";
        } else {
            model.addAttribute("info","登录失败！账户不存在或者密码错误！");
            return "user/error";
        }
    }

    /**
     * 登录主页
     * @return
     */
    @RequestMapping(value = "/welcome")
    public String welcome() {
        return "user/welcome";
    }

    /**
     * 订单修改页面
     * @return
     */
    @RequestMapping(value = "/update_page/order/{orderId}", method = RequestMethod.GET)
    public String updatePage(@PathVariable("orderId") int orderId, Model model) {
        model.addAttribute("orderUpdate", userService.getOrder(orderId));
        return "user/order/update";
    }


    /**
     * 下单页面
     * @return
     */
    @RequestMapping(value = "/order_page")
    public String orderPage() {
        return "user/order/order";
    }


    @RequestMapping("/login/out")
    public String loginOut(HttpSession session) {
        if (session.getAttribute("user") != null) {
            session.removeAttribute("user");
        }
        return "user/login";
    }

    /************************************** AJAX开始 ******************************************/

    @RequestMapping(value = "/order/page/ajax", method = RequestMethod.POST)
    @ResponseBody
    public JsonData orderUserPage(HttpSession session,@RequestBody PageInfo pageInfo) {
        User user = (User) session.getAttribute("user");
        Page<Order> orderPage = userService.userOrdersPage(user.getId(), pageInfo.getPage(), pageInfo.getSize());
        if (orderPage == null) {
            return JsonData.buildField("查询失败！");
        } else {
            return JsonData.buildSuccess(orderPage,"查询成功！");
        }
    }

    /**
     * 删除一条order
     * @param order
     * @return
     */
    @RequestMapping(value = "/delete/order/ajax", method = RequestMethod.POST)
    @ResponseBody
    public JsonData deleteOrderAjax(@RequestBody Order order) {
        if (userService.deleteOrder(order.getId())) {
            return new JsonData(JsonData.CODE_SUCCESS,null,"删除成功！");
        }
        return new JsonData(JsonData.CODE_FIELD,null,"删除失败！");
    }

    /**
     * 修改一条订单
     * @param order
     * @return
     */
    @RequestMapping(value = "/update/order/ajax", method = RequestMethod.POST)
    @ResponseBody
    public JsonData updateOrderAjax(@RequestBody Order order) {
        if (userService.updateOrder(order)) {
            return new JsonData(JsonData.CODE_SUCCESS,null,"更新成功！");
        }
        return new JsonData(JsonData.CODE_FIELD,null,"更新失败！");
    }

    /**
     * 新增一个订单
     * @param order
     * @param session
     * @return
     */
    @RequestMapping(value = "/order/ajax", method = RequestMethod.POST)
    @ResponseBody
    public JsonData orderAjax(@RequestBody Order order, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (userService.order(order.getName(),order.getPrice(),user.getId())) {
            return new JsonData(JsonData.CODE_SUCCESS,null,"更新成功！");
        }
        return new JsonData(JsonData.CODE_FIELD,null,"更新失败！");
    }

    /************************************** AJAX ******************************************/

    /*---------------------------------------------------------------------------------------------------------------------------------------------*/

    @ResponseBody
    @RequestMapping(value = "/ajax/test")
    public List<Order> ajaxTest() {
        return userService.userOrders(1);
    }

    /**
     * 用户登录检查测试1（使用viewAndModel）
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/check1", method = RequestMethod.POST, params = {"username","password"})
    public ModelAndView check1(String username, String password) {
        ModelAndView modelAndView = new ModelAndView();
        if (userService.login(username, password)) {
            modelAndView.addObject("user",userService.userInfo(username));
            modelAndView.setViewName("user/welcome");
        } else {
            modelAndView.addObject("info","登录失败！账户不存在或者密码错误！");
            modelAndView.setViewName("user/error");
        }
        return modelAndView;
    }

    /**
     * 解析器配置测试（xml，json）
     * @param model
     * @return
     */
    @RequestMapping(value = "/resolver")
    public String resolver(Model model) {
        User admin = userService.userInfo("admin");
        model.addAttribute("admin",admin);
        return "user/resolver";
    }

    /**
     * 文件上传测试页面
     * @return
     */
    @RequestMapping(value = "/file")
    public String file() {
        return "/user/file/index";
    }

    /**
     * 文件上传到服务器处理程序
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/file/put", method = RequestMethod.POST)
    public String filePut(@RequestParam("imgPath") MultipartFile file, MultipartHttpServletRequest request) throws IOException {
        //判断目录是否在服务器上，如果没有我们创建一个目录，并把上传文件放在目录下面
        if(!file.isEmpty()){
            String imgPath =  request.getSession().getServletContext().getRealPath("")
                    +file.getOriginalFilename();
            System.out.println(imgPath);
            //上传文件到指定目录
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(imgPath));
        }
        return "user/file/result";
    }
}